import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  List,
  Avatar,
  Button,
  Typography,
  Space,
  Divider,
  Tag,
  Pagination,
  Spin,
  message
} from 'antd';
import {
  EditOutlined,
  EyeOutlined,
  PlusOutlined,
  FileTextOutlined,
  UserOutlined,
  TrophyOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getUser } from '../../utils';
import BarChart from './components/BarChart';
import './Home.scss';

const { Title, Paragraph, Text } = Typography;

const Home = () => {
  const navigate = useNavigate();
  const [user] = useState(getUser());
  const [stats, setStats] = useState({
    totalArticles: 0,
    totalViews: 0
  });
  const [recentArticles, setRecentArticles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [articlesLoading, setArticlesLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0
  });

  // 获取统计数据
  const fetchStats = async () => {
    try {
      console.log('[前端] 请求统计数据');
      const response = await fetch('http://211.86.197.10:9091/api/stats');
      console.log('[前端] 统计数据响应状态:', response.status);
      
      // 检查HTTP状态
      if (!response.ok) {
        throw new Error(`HTTP错误: ${response.status}`);
      }
      
      // 检查响应是否为JSON
      const contentType = response.headers.get('content-type');
      console.log('[前端] 统计数据响应类型:', contentType);
      
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        console.error('API返回非JSON响应:', text.substring(0, 200));
        message.error('服务器响应格式错误，请检查服务器是否正常启动');
        return;
      }
      
      const result = await response.json();
      console.log('[前端] 统计数据结果:', result);
      
      if (result.success) {
        setStats(result.data);
      } else {
        message.error(result.message || '获取统计数据失败');
      }
    } catch (error) {
      console.error('获取统计数据错误:', error);
      message.error('获取统计数据失败，请检查网络连接和服务器状态');
    }
  };

  // 获取最近作品
  const fetchRecentArticles = async (page = 1, pageSize = 5) => {
    try {
      setArticlesLoading(true);
      console.log('[前端] 请求作品列表:', { page, pageSize });
      
      const response = await fetch(`http://211.86.197.10:9091/api/articles?page=${page}&limit=${pageSize}&status=published`);
      console.log('[前端] 响应状态:', response.status);
      
      // 检查HTTP状态
      if (!response.ok) {
        throw new Error(`HTTP错误: ${response.status}`);
      }
      
      // 检查响应是否为JSON
      const contentType = response.headers.get('content-type');
      console.log('[前端] 响应类型:', contentType);
      
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        console.error('API返回非JSON响应:', text.substring(0, 200));
        message.error('服务器响应格式错误，请检查服务器是否正常启动');
        return;
      }
      
      const result = await response.json();
      console.log('[前端] 解析结果:', result);
      
      if (result.success) {
        setRecentArticles(result.data.articles || []);
        setPagination({
          current: result.data.pagination.page,
          pageSize: result.data.pagination.limit,
          total: result.data.pagination.total
        });
      } else {
        message.error(result.message || '获取作品列表失败');
      }
    } catch (error) {
      console.error('获取作品列表错误:', error);
      message.error('获取作品列表失败，请检查网络连接和服务器状态');
    } finally {
      setArticlesLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([
        fetchStats(),
        fetchRecentArticles()
      ]);
      setLoading(false);
    };
    
    loadData();
  }, []);

  // 处理分页变化
  const handlePageChange = (page, pageSize) => {
    fetchRecentArticles(page, pageSize);
  };

  const chartData = {
    views: {
      title: '最近7天浏览量',
      xData: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      yData: [120, 200, 150, 80, 70, 110, 130]
    },
    articles: {
      title: '作品发布统计',
      xData: ['1月', '2月', '3月', '4月', '5月', '6月'],
      yData: [2, 5, 3, 8, 4, 6]
    }
  };

  const handleCreateArticle = () => {
    navigate('/create');
  };

  const handleViewArticle = (articleId) => {
    navigate(`/article-detail/${articleId}`);
  };

  const handleEditArticle = (articleId) => {
    navigate(`/create?id=${articleId}`);
  };

  const handleViewAllArticles = () => {
    navigate('/articles');
  };

  if (loading) {
    return (
      <div className="home-container" style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>加载中...</div>
      </div>
    );
  }

  return (
    <div className="home-container">
      {/* 欢迎区域 */}
      <Card className="welcome-card">
        <Row align="middle">
          <Col flex="auto">
            <Space direction="vertical" size="small">
              <Title level={2} style={{ margin: 0 }}>
                欢迎回来，{user?.username || '用户'}！
              </Title>
              <Paragraph style={{ margin: 0, color: '#666' }}>
                今天是个创作的好日子，开始写作你的精彩内容吧
              </Paragraph>
            </Space>
          </Col>
          <Col>
            <Button
              type="primary"
              size="large"
              icon={<PlusOutlined />}
              onClick={handleCreateArticle}
            >
              创建新作品
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 统计数据 */}
      <Row gutter={[16, 16]} className="stats-row">
        <Col xs={12} sm={12}>
          <Card>
            <Statistic
              title="总作品数"
              value={stats.totalArticles}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={12}>
          <Card>
            <Statistic
              title="总浏览量"
              value={stats.totalViews}
              prefix={<EyeOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        {/* 最近作品 */}
        <Col xs={24} lg={14}>
          <Card
            title="最近作品"
            extra={
              <Button type="link" onClick={handleViewAllArticles}>
                查看全部
              </Button>
            }
          >
            <Spin spinning={articlesLoading}>
              <List
                itemLayout="horizontal"
                dataSource={recentArticles}
                renderItem={article => (
                  <List.Item
                    actions={[
                      <Button
                        type="link"
                        onClick={() => handleViewArticle(article.id)}
                      >
                        查看
                      </Button>,
                      <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEditArticle(article.id)}
                      >
                        编辑
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={
                        <Avatar
                          src={article.cover_image}
                          shape="square"
                          size={64}
                          icon={<FileTextOutlined />}
                        />
                      }
                      title={
                        <div style={{ marginBottom: 8 }}>
                          <Button 
                            type="link" 
                            style={{ padding: 0, height: 'auto', marginRight: 8 }}
                            onClick={() => handleViewArticle(article.id)}
                          >
                            <Text strong>{article.title}</Text>
                          </Button>
                          <Tag color={article.status === 'published' ? 'green' : 'orange'}>
                            {article.status === 'published' ? '已发布' : '草稿'}
                          </Tag>
                        </div>
                      }
                      description={
                        <div style={{ marginRight: 120 }}>
                          <div style={{ marginBottom: 8 }}>
                            <Text type="secondary" ellipsis>
                              {article.content_html ? 
                                article.content_html.replace(/<[^>]*>/g, '').substring(0, 80) + '...' : 
                                '暂无内容'
                              }
                            </Text>
                          </div>
                          <Space size="large">
                            <Text type="secondary">
                              <EyeOutlined /> {article.view_count || 0}
                            </Text>
                            <Text type="secondary">
                              {new Date(article.created_at).toLocaleDateString()}
                            </Text>
                          </Space>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
              
              {recentArticles.length > 0 && (
                <div style={{ textAlign: 'center', marginTop: 16 }}>
                  <Pagination
                    current={pagination.current}
                    pageSize={pagination.pageSize}
                    total={pagination.total}
                    onChange={handlePageChange}
                    showSizeChanger={false}
                    showQuickJumper
                    showTotal={(total, range) => 
                      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                    }
                  />
                </div>
              )}
            </Spin>
          </Card>
        </Col>

        {/* 数据统计图表 */}
        <Col xs={24} lg={10}>
          <Card title="数据统计" className="chart-card">
            <div className="chart-container">
              <BarChart
                title={chartData.views.title}
                xData={chartData.views.xData}
                yData={chartData.views.yData}
              />
            </div>

            <Divider />

            <div className="chart-container">
              <BarChart
                title={chartData.articles.title}
                xData={chartData.articles.xData}
                yData={chartData.articles.yData}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 快捷操作 */}
      <Card title="快捷操作" className="quick-actions">
        <Row gutter={[16, 16]}>
          <Col xs={12} sm={8} md={6}>
            <Card
              hoverable
              className="action-card"
              onClick={handleCreateArticle}
            >
              <div className="action-content">
                <EditOutlined className="action-icon" />
                <Text strong>创建作品</Text>
              </div>
            </Card>
          </Col>
          <Col xs={12} sm={8} md={6}>
            <Card
              hoverable
              className="action-card"
              onClick={handleViewAllArticles}
            >
              <div className="action-content">
                <FileTextOutlined className="action-icon" />
                <Text strong>作品管理</Text>
              </div>
            </Card>
          </Col>
          <Col xs={12} sm={8} md={6}>
            <Card
              hoverable
              className="action-card"
              onClick={() => navigate('/profile')}
            >
              <div className="action-content">
                <UserOutlined className="action-icon" />
                <Text strong>个人资料</Text>
              </div>
            </Card>
          </Col>
          <Col xs={12} sm={8} md={6}>
            <Card
              hoverable
              className="action-card"
              onClick={() => navigate('/analytics')}
            >
              <div className="action-content">
                <TrophyOutlined className="action-icon" />
                <Text strong>数据分析</Text>
              </div>
            </Card>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default Home;